package org.ofbiz.crm.util;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.DelegatorFactory;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.model.ModelEntity;
import org.ofbiz.entity.model.ModelField;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javolution.util.FastList;

public class CrmUtils {
    public static String module = CrmUtils.class.getName();

    public static void main(String[] args) {
//	String s = "[{\"type\":3,\"values\":[\"187\"],\"formType\":\"mobile\",\"name\":\"mobile\"},{\"type\":4,\"values\":[\"126\"],\"formType\":\"text\",\"name\":\"email\"}]";
//	Map<String, Object> inputFields = FastMap.newInstance();
//	analysisMap(inputFields, s, "");
//	System.out.println(inputFields);
	System.out.println(getLastDate(2));
	System.out.println(getLastDateStr(2));
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static Map<String, Object> analysisMap(Map inputFields, String sceneData, String entityName) {
	JSONArray array = JSONArray.parseArray(sceneData);
	for (Object form : array) {
	    JSONObject data = (JSONObject) form;
	    int type = data.getIntValue("type");
	    String name = data.getString("name");
	    //name = name.replace("_dictText","");
	    String singleValue = data.getString("value");
	    
	    int index = 0;
	    index = getIndex(inputFields, name, index);
	    if (type == 1) {
		inputFields.put(name, singleValue);
	    } else if (type == 2) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "notEqual");
	    } else if (type == 3) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "contains");
	    } else if (type == 4) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "notContains");
	    } else if (type == 5) {
		inputFields.put(name + "_fld" + index + "_value", "");
		inputFields.put(name + "_fld" + index + "_op", "empty");
	    } else if (type == 6) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "greaterThan");
	    } else if (type == 7) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "greaterThanEqualTo");
	    } else if (type == 8) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "lessThan");
	    } else if (type == 9) {
		inputFields.put(name + "_fld" + index + "_value", singleValue);
		inputFields.put(name + "_fld" + index + "_op", "lessThanEqualTo");
	    }else if (type == 10) {
		inputFields.put(name + "_fld" + index + "_value", splitCustomStringToList(singleValue, ","));
		inputFields.put(name + "_fld" + index + "_op", "in");
	    }
	}
	
	
	Delegator delegator = DelegatorFactory.getDelegator("default");
	ModelEntity me = delegator.getModelEntity(entityName);
	inputFields = optimizingResults(inputFields, me);
	return inputFields;
    }
    
    
    
    public static Map<String, Object> optimizingResults(Map<String, Object> serviceResults, ModelEntity me) {
	try {
	    Iterator<ModelField> it = me.getFieldsIterator();
	    while (it.hasNext()) {
		ModelField pkf = it.next();
		String fieldName = pkf.getName();
		List<String> suffixList = UtilMisc.toList("_fld0_value", "_fld1_value","_value", "");
		for (String suffix : suffixList) {
		    Object pkValue = serviceResults.get(fieldName + suffix);
		    String type = pkf.getType();
		    if (UtilValidate.isNotEmpty(pkValue)) {
			String newFieldName = fieldName + suffix;
			if (type.equals("date-time")) {
			    if (!isValidDate(String.valueOf(pkValue))) {
				pkValue = pkValue + " 00:00:00";
			    }
			    serviceResults.put(newFieldName, Timestamp.valueOf(String.valueOf(pkValue)));
			} else if (type.equals("date") || type.equals("Date")) {
			    serviceResults.put(newFieldName,
				    java.sql.Date.valueOf(String.valueOf(serviceResults.get(newFieldName))));
			} else if (type.equals("time")) {
			    serviceResults.put(newFieldName,
				    java.sql.Time.valueOf(String.valueOf(serviceResults.get(newFieldName))));
			} else if (type.equals("currency-amount") || type.equals("currency-precise")
				|| type.equals("fixed-point")) {
			    serviceResults.put(newFieldName,
				    BigDecimal.valueOf(Double.valueOf(String.valueOf(serviceResults.get(newFieldName)))));
			} else if (type.equals("floating-point")) {
			    serviceResults.put(newFieldName,
				    Double.valueOf(String.valueOf(serviceResults.get(newFieldName))));
			} else if (type.equals("numeric")) {
			    serviceResults.put(newFieldName, Long.valueOf(String.valueOf(serviceResults.get(newFieldName))));
			} else if (type.equals("byte-array")) {
			    byte[] o = String.valueOf(serviceResults.get(newFieldName)).getBytes();
			    serviceResults.put(newFieldName, o);
			} else {
			    serviceResults.put(newFieldName, String.valueOf(serviceResults.get(newFieldName)));
			}
		    }
		}
	    }
	} catch (NumberFormatException e) {
	    Debug.logError(e.getMessage(), module);
	}

	return serviceResults;
    }
    public static String getNowDateStr() {
	Timestamp date = UtilDateTime.nowTimestamp();
	return date.toString().substring(0,10);
    }
    public static String getLastDateStr(Integer day) {
	Timestamp date = UtilDateTime.nowTimestamp();
	Calendar cal = Calendar.getInstance();  
        cal.setTime(date);
        cal.add(Calendar.DATE, (int)(day*-1));  
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");  
        String lastMonth = dft.format(cal.getTime());  
        return lastMonth;  
    }
    

    public static Timestamp getLastDate(Integer day) {
	Timestamp date = UtilDateTime.nowTimestamp();
	Calendar cal = Calendar.getInstance();  
        cal.setTime(date);
        cal.add(Calendar.DATE, (int)(day*-1));  
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");  
        String lastMonth = dft.format(cal.getTime());  
        Timestamp nowTime = Timestamp.valueOf(lastMonth);
        return nowTime;  
    }
    public static Timestamp getLastDateHms(Integer day) {
	Timestamp date = UtilDateTime.nowTimestamp();
	Calendar cal = Calendar.getInstance();  
        cal.setTime(date);
        cal.add(Calendar.DATE, (int)(day*-1));  
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");  
        String lastMonth = dft.format(cal.getTime()); 
        lastMonth = lastMonth + " 23:59:59";
        Timestamp nowTime = Timestamp.valueOf(lastMonth);
        return nowTime;  
    }
    public static boolean isValidDate(String str) {
	boolean convertSuccess = true;
	// 指定日期格式为四位年/两位月份/两位日期，注意yyyy/MM/dd区分大小写；
	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	try {
	    // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
	    format.setLenient(false);
	    format.parse(str);
	} catch (ParseException e) {
	    convertSuccess = false;
	}
	return convertSuccess;
    }

    @SuppressWarnings("rawtypes")
    public static int getIndex(Map inputFields, String field, int index) {
	if (UtilValidate.isNotEmpty(inputFields.get(field))) {
	    index = index + 1;
	}
	for (int i = 0; i < 30; i++) {
	    if (UtilValidate.isNotEmpty(inputFields.get(field + "_fld" + i + "_value"))) {
		index = index + 1;
	    } else {
		break;
	    }
	}
	return index;
    }
    
    @SuppressWarnings("rawtypes")
    public static List splitCustomStringToList(String inputString, String splitChar) {
	List result = FastList.newInstance();
	if (UtilValidate.isEmpty(inputString)) {
	    return result;
	}
	inputString = inputString.trim();
	String[] array = inputString.split(splitChar);
	for (int i = 0; i < array.length; i++) {
	    if (UtilValidate.isNotEmpty(array[i])) {
		result.add(array[i]);
	    }
	}
	return result;
    }
    
    
    
    public static String listUserLoginToSplitStringUserLoginId(List userLogin2List,String userLoginId1) {
        String userLoginId2=userLoginId1;
        for(int i=0;i<userLogin2List.size();i++){
            GenericValue m =(GenericValue)userLogin2List.get(i);
            userLoginId2 = userLoginId2 +","+m.getString("userLoginId");
            
        }
        return userLoginId2;
    }
   
    
    
}
